<template>
  <q-page class="q-pa-md wrapBox">
    <div class="nav">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <el-image src="/svgs/titleIcon.svg" style="width: 17px;margin-top: 2px" fit />
        </el-breadcrumb-item>
        <el-breadcrumb-item>数据中心</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ name: 'dataAnnotations' }">数据标注</el-breadcrumb-item>
        <el-breadcrumb-item><span style="color: #333;">新建标注任务</span></el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="datasetBox" style="position: relative">
      <div class="title">项目信息</div>
      <div class="contentBox">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm typeBox"
          style="max-width: 50%;" status-icon>
          <el-form-item label="任务名称：" prop="title">
            <el-input v-model.trim="ruleForm.title" placeholder="请输入任务名称" />
          </el-form-item>
          <el-form-item label="任务描述：">
            <el-input v-model="ruleForm.description" spellcheck="false" :rows="5" type="textarea" placeholder="请输入"
              show-word-limit maxlength="100" />
          </el-form-item>
          <el-form-item label="标注场景：" prop="label_type">
            <el-radio-group v-model="tabPosition" @change="handleRadioChange">
              <el-radio-button label="Sequence">序列/结构文件</el-radio-button>
              <el-radio-button label="Image">图片</el-radio-button>
              <el-radio-button label="TimeSeries">时序数据</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="标注类型：" prop="label_scene">
            <el-tabs :tab-position="tabPosition" style="margin-top: -30px;" class="demo-tabs ">
              <div class="row labelTypeBox labelTypeBoxData" v-show="tabPosition == 'Image'">
                <el-radio-group v-model="ruleForm.label_scene">
                  <el-radio-button v-for="(item, index) in imgOption" :key="index" :label="item.type"
                    @click="controlHide($event, item)">
                    <el-image :src="item.image_path" fit />
                    <div style="width: 100px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">{{ item.title }}
                    </div>
                  </el-radio-button>
                </el-radio-group>
              </div>
              <div class="row labelTypeBox labelTypeBoxData" v-show="tabPosition == 'TimeSeries'">
                <el-radio-group v-model="ruleForm.label_scene">
                  <el-radio-button v-for="(item, index) in dataOption" :key="index" :label="item.type"
                    @click="controlHide($event, item)">
                    <el-image :src="item.image_path" fit />
                    <div style="width: 100px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">{{ item.title }}</div>
                  </el-radio-button>
                </el-radio-group>
              </div>
              <div class="row labelTypeBox labelTypeBoxText" v-show="tabPosition == 'Sequence'">
                <el-radio-group v-model="ruleForm.label_scene">
                  <el-radio-button v-for="(item, index) in textOption" :key="index" :label="item.type"
                    @click="controlHide($event, item)">
                    <el-image :src="item.image_path" fit />
                    <div style="width: 100px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">{{ item.title }}
                    </div>
                  </el-radio-button>
                </el-radio-group>
              </div>
            </el-tabs>
          </el-form-item>
          <el-form-item label="数据集名称：" prop="dataset_id" style="width: 700px;">
            <el-select v-loadMore="getMoreData" style="margin-right: 10px;max-height: 300px; overflow-y: auto;" v-model="ruleForm.dataset_id"
              class="m-2 more_dropdown_select" placeholder="请选择数据集名称" popper-class="more_dropdown_select">
              <el-option v-for="item in optionsList" :key="item.title" :label="item.title" :value="item.id"
                @click="chooseDataset(item.id, '1')" />
              <div v-if="loadingMoreState" class="selectMoreData">
                <el-icon class="is-loading">
                  <Loading />
                </el-icon>加载更多
              </div>
            </el-select>
          </el-form-item>
          <el-form-item label="数据集版本：" v-if="ruleForm.dataset_id" prop="version_id" style="width: 700px;">
            <el-select  v-loadData="getMoreVersion"  class="more-select" popper-class="more_select_Data" v-model="ruleForm.version_id" placeholder="请选择版本">
              <el-option v-for="item in optionsList1" :key="item.id" :label="item.title" :value="item.id" />
              <div v-if="loadingMoreVersion" class="selectMoreData">
                <el-icon class="is-loading">
                  <Loading />
                </el-icon>加载更多
              </div>
            </el-select>
          </el-form-item>
          <el-form-item label="添加标签集：" style="width: 700px;">
            <el-input v-model.trim="dataSetLabel" placeholder="请输入标签名称" style="width: 300px;margin-right: 10px;" />
            <el-color-picker v-model="elColor" />
            <el-button type="primary" size="small" style="margin-left: 7px;" @click="addTabs()">添加数据</el-button>
            <el-table :data="ruleForm.labels" style="width: 300px;" max-height="150" :show-header="false"
              v-if="ruleForm.labels.length > 0">
              <el-table-column prop="value" label="value" />
              <el-table-column prop="background" label="background" />
              <el-table-column fixed="right" label="Operations" width="70">
                <template #default="scope">
                  <el-button link type="primary" size="small" @click.prevent="deleteRow(scope.$index)">
                    <el-icon>
                      <Close />
                    </el-icon>
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form>
        <div style="height: 10px;width: 100%;background-color: #f6f8fa"></div>
        <div class="row" style="display:flex;justify-content: flex-end;margin-top: 10px">
          <el-button v-if="!store.quickStart.quickFlow" @click="resetForm(ruleFormRef)"
            style="background-color: #fff!important;">取消</el-button>
          <el-button v-if="!store.quickStart.quickFlow" type="primary" @click="submitForm(ruleFormRef)">
            创建任务
          </el-button>
          <el-button v-if="store.quickStart.quickFlow" type="primary" @click="submitForm(ruleFormRef)">
            下一步
          </el-button>
        </div>
      </div>
    </div>
  </q-page>
</template>


<script setup lang="ts">

import { ref, reactive, shallowRef, onMounted, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import type { FormInstance, FormRules } from 'element-plus'
import {
  typeOfDataset,
  versionManage,
  dataLabel,
  validateTaskTitle,
  getVersion,
  searchDataLabel,
  getDatasetList
} from 'src/api/dataset'
import { ElMessageBox, ElMessage } from 'element-plus'
import { getDatalabelListApi } from 'src/api/common'
import { evaSlash } from "@quasar/extras/eva-icons";
import { dataSetStore } from 'src/stores/dataSet'
const store = dataSetStore()
const router = useRouter()
const loading = ref(false)
const projectId = router.currentRoute.value.params.project_id
const ruleFormRef = ref<FormInstance>()
const elColor = ref('#409EFF')
const ruleForm = reactive({
  title: '',
  description: '',
  label_type: '',
  label_scene: '',
  dataset_id: '',
  version_id: '',
  labels: <any>[],
})
import vLoadMore from 'src/utils/loadMore';
import vLoadData from 'src/utils/LoadMoreData';
const dataSetLabel = ref('');
const sources = ref('exercise')

const versionData = ref({
  count: 0,
  results: <any>[]
})
const loadingMoreState = ref(false);
const loadingMoreVersion = ref(false);
const pageData = ref({page: 1});
const pageData1 = ref({page: 1});
const optionsList = ref(<any>[]);
const optionsList1 = ref(<any>[]);
const versionId = ref(0);
const dataSetList = ref({
  count: 0,
  results: <any>[]
});
const validateTitle = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('任务名称不能为空'))
    return
  }
  let params = {
    title: ruleForm.title
  }
  validateTaskTitle(projectId, params).then((res: any) => {
    if (res.data.msg) {
      callback(new Error('已存在此任务名称'))
    }
    callback()
  }).catch((err: any) => {
    callback(new Error('校验接口报错'))
  })
}
const rules = reactive<FormRules>({
  title: [
    { required: true, validator: validateTitle, trigger: 'blur' }
  ],
  label_type: [
    { required: true, message: '标注场景不能为空', trigger: 'blur' }
  ],
  label_scene: [
    { required: true, message: '标注类型不能为空', trigger: 'blur' }
  ],
  dataset_id: [
    { required: true, message: '数据集名称不能为空', trigger: 'change' }
  ],
  version_id: [
    { required: true, message: '数据集版本不能为空', trigger: 'change' }
  ]
})
initOption()
function initOption() {
  loading.value = true
  getDatalabelListApi().then((res) => {
    imgOption.value = filterType(res.data, 'Image', 'data_type');
    dataOption.value = filterType(res.data, 'TimeSeries', 'data_type')
    textOption.value = filterType(res.data, 'Text', 'data_type').filter((item: any) => {
      if (item.type === 'machine_translation' || item.type === 'question_answering' || item.type === 'taxonomy') {
        return false
      } else {
        return true
      }
    })
    loading.value = false
  })
}
function filterType(arr: any, str: string, type: any) {
  let newArr = arr.filter((item: any, index: number) => {
    if (item[type] == str) return item
  })
  return newArr
}
// 控制数据集标签和choices显示
function controlHide(e: any, item: any) {
  // ruleForm.data_format = item.data_format
  dataSetLabel.value = ''
  if (e.target.tagName === 'INPUT') return
}

const tabPosition = ref('Image')
// 图片
let imgOption: any = ref([])
// 标注场景时序数据
let dataOption: any = ref([])
// 标注场景文本
let textOption: any = ref([])
const getMoreData = async () => {
  if (pageData.value.page < (dataSetList.value.count) / 10) {
    loadingMoreState.value = true
    pageData.value.page++;
    initPageEvent(tabPosition.value);
    loadingMoreState.value = false
  }
}
//页面初始化事件
initPageEvent(tabPosition.value);
function initPageEvent(val:any){
  //获取数据集列表
  let obj: any = { dataset_type: val };
  obj = Object.assign(obj, pageData.value);
  if( pageData.value.page = 1 ){
    optionsList.value = [];
  }
  getDatasetList(projectId,obj).then( (res:any) =>{
    dataSetList.value = res.data;
    optionsList.value = optionsList.value.concat(dataSetList.value.results)
  })
}
function handleRadioChange(value: any) {
  pageData.value.page = 1;
  ruleForm.dataset_id = '';
  ruleForm.version_id = '';
  dataSetLabel.value = '';
  ruleForm.labels = [];
  initPageEvent(value);
}

function chooseDataset(id: number,nums:string) {
  versionId.value = id;
  if( nums === '1' ){
    pageData1.value.page = 1;
    optionsList1.value = [];
  }
  versionManage(projectId,id,pageData1.value).then( (res:any) =>{
    versionData.value = res.data;
    optionsList1.value = optionsList1.value.concat(versionData.value.results)
  })
}

const getMoreVersion = async ()=>{
  if (pageData1.value.page < (versionData.value.count) / 10) {
    loadingMoreVersion.value = true
    pageData1.value.page++;
    chooseDataset(versionId.value,'2');
    loadingMoreVersion.value = false
  }
}


const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  router.push({ name: 'dataAnnotations', params: { project_id: projectId } })
}


const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  if (tabPosition.value === 'Sequence') {
    ruleForm.label_type = 'Text';
  } else {
    ruleForm.label_type = tabPosition.value;
  }
  await formEl.validate((valid, fields) => {
    if (valid) {
      const arrayList: any[] = [];
      if (
        ruleForm.label_scene === 'outliers_and_anomaly_detection' ||
        ruleForm.label_scene === 'time_series_forecasting'
      ) {
        let fromData = JSON.parse(JSON.stringify(ruleForm));
        fromData.labels.forEach((item: any) => {
          arrayList.push({
            value: item.value,
            background: item.background,
          })
        })
        ruleForm.choices = arrayList;
      }
      if (
        ruleForm.label_scene === 'image_classification' ||
        // ruleForm.label_scene === 'outliers_and_anomaly_detection' ||
        ruleForm.label_scene === 'signal_quality' ||
        // ruleForm.label_scene === 'time_series_forecasting' ||
        ruleForm.label_scene === 'taxonomy' ||
        ruleForm.label_scene === 'text_classification'
      ) {
        let fromData = JSON.parse(JSON.stringify(ruleForm));
        fromData.labels.forEach((item: any) => {
          arrayList.push({
            value: item.value,
            background: item.background,
          })
        })
        ruleForm.choices = arrayList;
        delete ruleForm.labels;
      }
      dataLabel(projectId, ruleForm).then((res: any) => {
        ElMessageBox.alert('创建数据标注任务成功', '提示', {
          confirmButtonText: '知道了',
          autofocus: false
        }).then(() => {
          if (store.quickStart.quickFlow) {
            searchDataLabel(projectId, { title: res.data.title }).then((el: any) => {
              let resultObj = el.data.results[0]
              store.setUseData(resultObj.id, resultObj.annotation_config, resultObj.label_type,resultObj.title)
              store.taskId(resultObj.id)
              if (
                resultObj.label_scene === 'image_classification' ||
                resultObj.label_scene === 'taxonomy' ||
                resultObj.label_scene === 'text_classification'
              ) {
                store.setLabelsArr(resultObj.choices)
              } else {
                store.setLabelsArr(resultObj.labels)
              }
              router.push({ name: 'dataAnnotations-dimension', params: { project_id: projectId } })
            }).catch(error => {
              console.log('出现错误，请重试')
            })

          } else {
            router.push({ name: 'dataAnnotations', params: { project_id: projectId } })
          }
        }).catch(error => {
          console.log(error)
        })
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}
function addTabs() {
  let isHave = true
  if (ruleForm.labels.length > 0) {
    isHave = ruleForm.labels.every((item: any) => {
      return item.value != dataSetLabel.value
    })
  }
  if (dataSetLabel.value.length > 0) {
    if (isHave == true) {
      ruleForm.labels.push({
        value: dataSetLabel.value,
        background: elColor.value
      })
      dataSetLabel.value = ''
    } else {
      ElMessage.error('标签集名称重复，请更改')
    }
  } else {
    ElMessage.error('请输入标签名称')
  }
}
const deleteRow = (index: number) => {
  ruleForm.labels.splice(index, 1)
}
</script>

<style scoped lang="scss">
.nav {
  display: flex;
  align-items: center;
  padding-left: 20px;
  cursor: pointer;
  background-color: #f6f8fa;
  height: 46px;

  ::v-deep .el-breadcrumb {
    display: flex;
    align-items: center;
  }
}

.wrapBox {
  padding: 0 !important;

  .datasetBox {
    margin: 0 20px;

    .title {
      width: 100%;
      padding: 12px;
      box-sizing: border-box;
      background-color: #fff;
      color: #333;
      font-size: 16px;
      font-weight: 500;
      text-align: left;
      line-height: 24px;
      border-bottom: 2px solid #f6f8fa;
    }

    .contentBox {
      padding: 12px;
      background-color: #ffffff !important;
    }
  }
}

//下拉框背景颜色
.dropdown {

  .el-select-dropdown__item.hover,
  .el-select-dropdown__item:hover {
    background: #3d5ce41a;
    color: #3d5ce4;
    font-weight: 400;
    font-size: 14px;
    text-align: left;
  }
}

::v-deep .el-form-item__label {
  color: #333;
}

//间距
.el-form-item {
  margin-bottom: 30px;
}

//面包屑斜杆
::v-deep .el-breadcrumb__separator {
  font-size: 12px !important;
  color: #c9cdd4 !important;
  margin-top: 2px !important;
}

:deep(.el-input__inner::placeholder),
:deep(.el-textarea__inner::placeholder) {
  color: #cccccc;
  font-size: 14px;
  font-weight: 400;
}

::v-deep .el-breadcrumb__inner.is-link,
.el-breadcrumb__inner a {
  font-weight: normal !important;
}

//tab选项卡 start
::v-deep .el-radio-button__original-radio:checked+.el-radio-button__inner {
  background: #3d5ce41a !important;
  color: #3d5ce4 !important;
}

::v-deep .el-radio-button__inner {
  width: 150px !important;
  background: #fafafa !important;
}

//end
//数据标注-标注类型
.labelTypeBox {
  .el-radio-button {
    margin-right: 20px;
    margin-top: 20px;

    // 自定义单选框样式
    &::v-deep .el-radio-button__inner {
      border-radius: 4px;
      border-left: 1px solid #dcdfe6;
    }

    &::v-deep .el-radio-button__original-radio:checked+.el-radio-button__inner {
      background-color: white;
      color: #3D5CE4;
      border-color: #3D5CE4;
      border-left: 1px solid #3D5CE4;
      box-shadow: none;
    }
  }

}

.labelTypeBoxText,
.labelTypeBoxData {
  width: 70vw;

  .el-image {
    width: 100px;
    height: 80px;
  }

  .el-radio-button {
    margin-right: 20px;

    // 自定义单选框样式
    &::v-deep .el-radio-button__inner {
      border-radius: 4px;
      border-left: 1px solid #dcdfe6;
      font-size: 12px;
    }
  }
}



.versionSelect {
  &::v-deep .el-input__validateIcon {
    display: none;
  }
}

.selectMoreData {
  text-align: center;
  padding: 5px 0;
  border-top: 1px solid #f6f6f6;
  color: #aaa;

  .el-icon {
    vertical-align: middle;
    margin: -2px 2px 0 0;
    font-size: 16px;
  }
}
</style>
